package com.hong.arithmetic.cas;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author: csh
 * @Date: 2022/8/6 21:03
 * @Description:cas实现验证
 */
public class CasStudy {
    public static void main(String[] args) {
        CasV1 casV1 = new CasV1();
        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int defaultValue = casV1.getValue();
                    int newValue = (int) (Math.random() * 10000);
                    boolean setResult = casV1.compareAndSet(defaultValue,newValue );
                    System.out.println("新值："+newValue+"设置结果为：" + setResult);
                }
            }).start();
        }

        //解决ABA问题的版本
        CasV2 casV2 = new CasV2(new AtomicReference<>(10));
        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int defaultValue = casV2.getValue();
                    int newValue = (int) (Math.random() * 10000);
                    boolean setResult = casV2.compareAndSet(defaultValue,newValue );
                    System.out.println("ABA版本新值："+newValue+"设置结果为：" + setResult);
                }
            },"ABA").start();
        }
    }
}
